//
// Created by PulsarV on 18-11-11.
//

#include <stdio.h>
#include <cstring>
#include <mpi.h>
#include <opencv2/opencv.hpp>
#include <zconf.h>


int main(int argc, char *argv[]) {
    int rank, size, len;

    char version[MPI_MAX_LIBRARY_VERSION_STRING];
    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Get_library_version(version, &len);
    std::string name = version;
    if (rank == 0) {
        cv::VideoCapture cap(0);
        std::cout << "Open Camera In Rank:" << rank << std::endl << std::endl;
        while (true) {
            cv::Mat frame;
            cap >> frame;
            cv::imshow("master", frame);
            std::vector<uchar> data_encode;
            cv::imencode(".png", frame, data_encode);
            int buffer_size = 640 * 480 * 3;
            auto *t_data = new u_char[buffer_size];
            memset(t_data, 0, buffer_size);
            memcpy(t_data, data_encode.data(), data_encode.size());
            MPI_Send(t_data, buffer_size, MPI_UNSIGNED_CHAR, 1, 28, MPI_COMM_WORLD);
            cv::waitKey(1);
            free(t_data);
        }
    }
    if (rank == 1) {
        while (true) {
            int buffer_size = 640 * 480 * 3;
            u_char *t_data = new u_char[buffer_size];
            MPI_Recv(t_data, buffer_size, MPI_UNSIGNED_CHAR, 0, 28, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
            std::vector<uchar> data(t_data,t_data+buffer_size-1);
            cv::Mat img_decode = cv::imdecode(data, CV_32FC3);
            imshow("slaver",img_decode);
            cv::waitKey(1);
            free(t_data);
        }
    }
//    std::cout<<name<<"is_node:"<<is_master<<std::endl;
    printf("CV caculator %d of %d, (%s, %d)\n", rank, size, version, len);
    MPI_Finalize();
}


